<template>
	<cl-dialog
		title="管理门店"
		width="650px"
		:visible.sync="visible"
		:before-close="beforeClose"
		@close="close"
		:props="{
			top: '5vh',
			closeOnClickModal: false
		}"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-form-item label="管理门店" prop="is_assign" required>
				<el-radio-group v-model="form.is_assign" @change="treeExpand">
					<el-radio :label="0">全部</el-radio>
					<el-radio :label="1">指定</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="指定门店" v-if="form.is_assign == 1">
				<template #label>
					<span style="color: #f56c6c">*</span>
					指定门店
					<el-input
						placeholder="请输入门店名称"
						class="filterNode"
						clearable
						v-model="filterText"
					/>
				</template>
				<!-- <el-checkbox-group v-model="form.manage_dept_ids">
					<el-row>
						<el-col :span="8" v-for="(item, index) in shopList" :key="index">
							<el-checkbox :label="item.dept_id" name="manage_dept_ids">
								{{ item.dept_name }}
							</el-checkbox>
						</el-col>
					</el-row>
				</el-checkbox-group> -->
				<el-form-item prop="manage_dept_ids">
					<el-tree
						:class="[browser.isMobile ? 'mobile-tree' : 'pc-tree']"
						ref="tree"
						:data="shopList"
						:default-checked-keys="form.manage_dept_ids"
						node-key="dept_id"
						show-checkbox
						highlight-current
						default-expand-all
						@check="treeCheckChange"
						@node-expand="treeExpand"
						:render-content="renderContent"
						:filter-node-method="filterNode"
						:props="{
							value: 'dept_id',
							label: 'full_name'
						}"
					/>
					<input type="hidden" v-model="form.manage_dept_ids" />
				</el-form-item>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="close">关闭</el-button>
			<el-button type="primary" @click="submit" :loading="saving">确定</el-button>
		</template>
	</cl-dialog>
</template>
<script>
import { mapGetters } from "vuex";
import { addClass } from "@/utils";
export default {
	name: "manage-store",
	data() {
		return {
			visible: false,
			form: {
				user_id: "",
				is_assign: 0, // 是否指定
				manage_section_id: "",
				manage_biz_id: "",
				manage_channel_id: "",
				manage_dept_ids: [],
				manage_dept_id: ""
			},
			rules: {
				manage_dept_ids: [{ required: true, message: "请选择门店" }]
			},
			saving: false,
			filterText: "",
			info: {}
		};
	},
	watch: {
		filterText(val) {
			this.$refs.tree.filter(val);
		}
	},
	computed: {
		...mapGetters(["browser"]),
		shopList() {
			const { biz_id } = this.info;
			return this.getBizRefData(biz_id, "shop");
		}
	},
	methods: {
		async open(data = {}) {
			this.visible = true;
			this.info = { ...data };
			Object.keys(this.form).forEach(key => {
				this.form[key] = data[key];
			});
			let is_assign = data.manage_dept_id == "*" ? 0 : 1;
			this.form.is_assign = is_assign;
			await this.getShopList(data.biz_id);
			let manage_dept_ids =
				is_assign == 0
					? []
					: (data.manage_dept_id || "")
							.split(",")
							.filter(Boolean)
							.map(Number);
			let check_ids = this.filterChecks(manage_dept_ids);
			this.form.manage_dept_ids = check_ids;
		},
		// 处理选中的数据
		filterChecks(ids) {
			const { is_assign } = this.form;
			if (is_assign == 0) return [];
			let result = [];
			let deep = (list, index = 0, parent) => {
				for (let i = 0; i < list.length; i++) {
					const item = list[i];
					let children = item?.children || [];
					deep(children, index + 1, parent);
					let check_ids = children
						.filter(v => ids.includes(v.dept_id))
						.map(v => v.dept_id);
					result.push(...check_ids);
					if (index == 0 && ids.includes(item.dept_id) && !check_ids.length) {
						result.push(item.dept_id);
					}
					if (parent && check_ids.length == children.length) {
						result.push(parent.dept_id);
					}
				}
			};
			deep(this.shopList, 0);
			return result;
		},
		beforeClose(done) {
			if (this.saving) return;
			done();
		},
		close() {
			if (this.saving) return;
			this.visible = false;
			this.reset();
		},
		reset() {
			this.saving = false;
			this.filterText = "";
			this.$refs.form.resetFields();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				try {
					this.saving = true;
					const { is_assign, manage_dept_ids, ...args } = this.form;
					let check_ids = this.filterChecks(manage_dept_ids);

					let form = {
						...args,
						manage_dept_id: is_assign ? check_ids.join() : "*"
					};
					await this.$service.user.manage(form);
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.saving = false;
					this.close();
				} catch (error) {
					this.saving = false;
				}
			});
		},
		filterNode(value, data) {
			if (!value) return true;
			return data.dept_name.indexOf(value) !== -1;
		},
		// 门店
		async getShopList(biz_id) {
			const data = await this.getBizRefShop(biz_id);
			this.treeExpand();
		},
		treeCheckChange(data, { checkedKeys }) {
			this.form.manage_dept_ids = checkedKeys;
			this.$refs.form.validateField("manage_dept_ids");
		},
		//节点被展开时触发的事件
		treeExpand() {
			//因为该函数执行在renderContent函数之前，所以得加定时
			setTimeout(() => {
				this.changeCss();
			}, 10);
		},
		//点击修改添加样式
		changeCss() {
			let levelName = document.getElementsByClassName("foo"); // levelname是上面的最底层节点的名字
			for (let i = 0; i < levelName.length; i++) {
				let ele = levelName[i].parentNode;
				addClass(ele, "need-float");
				addClass(ele.parentNode, "need-float-parent");
			}
		},
		//树节点的内容区的渲染 Function
		renderContent(h, { node }) {
			let classname = "";
			// 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
			if (node.level === 3) {
				classname = "foo ellipsis";
			}
			if (node.level === 2 && node.childNodes.length === 0) {
				classname = "foo ellipsis";
			}
			return h("p", { class: classname }, node.label);
		}
	}
};
</script>
<style lang="scss" scoped>
::v-deep {
	.el-dialog__body {
		max-height: 70vh;
		overflow: auto;
	}
	.mobile-tree {
		.need-float {
			width: 100% !important;
		}
	}
	.el-tree {
		margin: 12px 0;
		.need-float {
			float: left;
			width: 30%;
			background-color: #fff !important;
		}
		&-node {
			/*display: inline-block;*/
			&__content::before {
				content: "";
				padding-left: 10px;
			}
			.el-checkbox__input {
				margin-right: 6px;
			}
		}
	}
}
.filterNode {
	width: 160px;
	margin-left: 10px;
	// border-radius: 4px;
	// border: 1px solid #dcdfe6;
	// box-sizing: border-box;
	// color: #606266;
	// display: inline-block;
	// font-size: inherit;
	// text-indent: 1em;
}
</style>
